import { deleteItem, selectPage } from '@/services/sales/integralGoods';
import { ProTable } from '@ant-design/pro-components';
import { useDispatch, useSelector } from '@umijs/max';
import { useRequest } from 'ahooks';
import { Button, Modal } from 'antd';
import { useEffect, useRef } from 'react';
import Add from './Details/Add';
import Edit from './Details/Edit';
import { columns } from './columns';

import { isShowButton } from '@/utils/util';

const currentPermissions = JSON.parse(localStorage.getItem('currentPermissions'));

export default () => {
  // const { modal } = App.useApp();
  const ref = useRef();
  const dispatch = useDispatch();
  const { reload, selectedRowKeys } = useSelector((state) => state.integralGoods);
  const update = (data) => {
    dispatch({
      type: 'integralGoods/update',
      payload: data,
    });
  };

  // 新增编辑刷新分页
  useEffect(() => {
    dispatch({ type: 'integralGoods/selectByAgentCompany' });
    if (reload) ref?.current?.reload();
  }, [reload]);

  const { run: mutateDeleteAsync } = useRequest(deleteItem, {
    manual: true,
    onSuccess: ({ code }) => {
      if (code === 200) {
        ref?.current?.reload();
      }
    },
  });

  // 操作
  const handleEdit = (type, record) => {
    update({ type });
    if (type === 'add') {
      update({ visible: true, editData: {} });
    }
    if (type === 'edit') {
      update({
        editVisible: true,
        editData: record || {},
      });
    }
    if (type === 'delete') {
      Modal.confirm({
        title: '温馨提醒',
        maskClosable: true,
        content: '删除后该商品将不参与积分兑换，是否删除？',
        onOk: () => mutateDeleteAsync({ ids: [record.id] }),
      });
    }
    if (type === 'batchDelete') {
      Modal.confirm({
        title: '温馨提醒',
        maskClosable: true,
        content: '批量删除后选中商品将不参与积分兑换，是否删除？',
        onOk: () => mutateDeleteAsync({ ids: selectedRowKeys }),
      });
    }
  };

  return (
    <div>
      <ProTable
        headerTitle="积分商品列表"
        actionRef={ref}
        options={false}
        search={{
          labelWidth: 'auto',
        }}
        request={async (params = {}) => {
          const { current, pageSize, ...formData } = params;
          let body = {
            pageNum: current,
            pageSize,
            ...formData,
          };
          const { code, data, total } = await selectPage(body);
          if (code && code === 200) {
            update({ reload: false, selectedRowKeys: [], selectedRows: [] });
            return {
              data: data || [],
              total: total,
              success: true,
            };
          }
        }}
        toolBarRender={() => [
          <>
            {isShowButton(currentPermissions, 'sales:integralGoods:remove') && (
              <Button
                key="add"
                disabled={!selectedRowKeys || selectedRowKeys.length === 0}
                type="primary"
                onClick={() => handleEdit('batchDelete')}
              >
                批量删除
              </Button>
            )}
          </>,
          <>
            {isShowButton(currentPermissions, 'sales:integralGoods:add') && (
              <Button key="batchDelete" type="primary" onClick={() => handleEdit('add')}>
                新增
              </Button>
            )}
          </>,
        ]}
        pagination={{
          showSizeChanger: true,
        }}
        cardProps={{
          size: 'small',
          style: {
            padding: 0,
          },
        }}
        cardBordered={true}
        columns={columns({ handleEdit, currentPermissions })}
        rowKey="id"
        rowSelection={{
          selectedRowKeys: selectedRowKeys,
          onChange: (selectedRowKeys, selectedRows) => {
            update({ selectedRowKeys: selectedRowKeys, selectedRows: selectedRows });
          },
        }}
      />
      <Add />
      <Edit />
    </div>
  );
};
